<template>
  <div class="credits-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>学分查询</span>
          <el-select
            v-model="filterYear"
            placeholder="选择学年"
            style="width: 180px"
            @change="handleYearChange"
          >
            <el-option
              v-for="item in yearOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
      </template>
      
      <!-- 学分总览 -->
      <div class="credit-overview">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="stat-card total-credits">
              <div class="stat-icon">
                <el-icon><DataLine /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-title">已修总学分</div>
                <div class="stat-value">{{ creditStats.earnedCredits }}</div>
                <div class="stat-description">
                  毕业要求：{{ creditStats.requiredCredits }}学分
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-card gpa">
              <div class="stat-icon">
                <el-icon><StarFilled /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-title">平均绩点(GPA)</div>
                <div class="stat-value">{{ creditStats.gpa }}</div>
                <div class="stat-description">
                  累计共修 {{ creditStats.totalCourses }} 门课程
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-card remaining">
              <div class="stat-icon">
                <el-icon><WarningFilled /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-title">毕业学分缺口</div>
                <div 
                  class="stat-value" 
                  :class="{ 'warning-value': creditStats.remainingCredits > 0 }"
                >
                  {{ creditStats.remainingCredits > 0 ? creditStats.remainingCredits : '0' }}
                </div>
                <div class="stat-description">
                  {{ creditStats.remainingCredits > 0 ? '还需修读学分' : '已达到毕业要求' }}
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <!-- 学分进度 -->
      <div class="credit-progress">
        <h3>毕业要求达成进度</h3>
        <el-row :gutter="20">
          <el-col :span="24">
            <div class="progress-item">
              <div class="progress-header">
                <span>总学分进度</span>
                <span>{{ creditStats.earnedCredits }}/{{ creditStats.requiredCredits }}</span>
              </div>
              <el-progress 
                :percentage="creditStats.creditProgress || 0" 
                :stroke-width="15" 
                :format="percentFormat"
              />
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" class="category-progress">
          <el-col :span="12" v-for="(category, index) in creditCategories" :key="index">
            <div class="progress-item">
              <div class="progress-header">
                <span>{{ category.name }}</span>
                <span>{{ category.earned }}/{{ category.required }}</span>
              </div>
              <el-progress 
                :percentage="category.required ? (category.earned / category.required) * 100 : 0" 
                :stroke-width="10" 
                :color="getCategoryColor(index)"
                :format="percentFormat"
              />
              <div class="progress-description">
                {{ category.description }}
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <!-- 学分分布图 -->
      <div class="credit-distribution">
        <h3>学分分布统计</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <div ref="yearDistributionChart" class="chart-container"></div>
          </el-col>
          <el-col :span="12">
            <div ref="categoryDistributionChart" class="chart-container"></div>
          </el-col>
        </el-row>
      </div>
      
      <!-- 学分明细 -->
      <div class="credit-details">
        <h3>学分获取明细</h3>
        <el-table :data="filteredCreditRecords" style="width: 100%">
          <el-table-column prop="semester" label="学期" width="160" />
          <el-table-column prop="courseCode" label="课程代码" width="120" />
          <el-table-column prop="courseName" label="课程名称" min-width="200" />
          <el-table-column prop="category" label="课程类别" width="120" />
          <el-table-column prop="credit" label="学分" width="80" align="center" />
          <el-table-column prop="grade" label="成绩" width="80" align="center">
            <template #default="scope">
              <span :class="{ 'failed-grade': scope.row.grade < 60 }">
                {{ scope.row.grade }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag 
                :type="scope.row.status === '已通过' ? 'success' : 'danger'"
                effect="plain"
              >
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { DataLine, StarFilled, WarningFilled } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import studentApi from '@/api/modules/student'

// 筛选条件
const filterYear = ref('all')

// 图表引用
const yearDistributionChart = ref(null)
const categoryDistributionChart = ref(null)

// 学年选项
const yearOptions = [
  { label: '全部学年', value: 'all' },
  { label: '2022-2023学年', value: '2022-2023' },
  { label: '2021-2022学年', value: '2021-2022' },
  { label: '2020-2021学年', value: '2020-2021' }
]

// API数据
const creditStats = ref({})
const creditCategories = ref([])
const creditRecords = ref([])

// 页面加载时获取数据
const fetchCredits = async () => {
  const { data } = await studentApi.getCredits({ year: filterYear.value })
  creditStats.value = data.creditStats
  creditCategories.value = data.creditCategories
  creditRecords.value = data.creditRecords
}

onMounted(() => {
  fetchCredits()
})

// 监听学年切换
const handleYearChange = (value) => {
  fetchCredits()
}

// 过滤后的学分记录
const filteredCreditRecords = computed(() => {
  if (filterYear.value === 'all') {
    return creditRecords.value
  } else {
    return creditRecords.value.filter(record => record.semester.includes(filterYear.value))
  }
})

// 百分比格式化
const percentFormat = (percentage) => {
  return percentage.toFixed(1) + '%'
}

// 获取类别颜色
const getCategoryColor = (index) => {
  const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C']
  return colors[index % colors.length]
}

// 初始化年度学分分布图表
const initYearDistributionChart = () => {
  const chartInstance = echarts.init(yearDistributionChart.value)
  
  const option = {
    title: {
      text: '各学年学分分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}: {c} 学分'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['2020-2021', '2021-2022', '2022-2023', '2023-2024']
    },
    yAxis: {
      type: 'value',
      name: '学分'
    },
    series: [
      {
        name: '学分',
        type: 'bar',
        data: [35, 42, 28, 15],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#2378f7' },
              { offset: 0.7, color: '#2378f7' },
              { offset: 1, color: '#83bff6' }
            ])
          }
        }
      }
    ]
  }
  
  chartInstance.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    chartInstance.resize()
  })
}

// 初始化类别学分分布图表
const initCategoryDistributionChart = () => {
  const chartInstance = echarts.init(categoryDistributionChart.value)
  
  const option = {
    title: {
      text: '各类别学分分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} 学分 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
    },
    series: [
      {
        name: '学分分布',
        type: 'pie',
        radius: '60%',
        center: ['50%', '60%'],
        data: [
          { value: 32, name: '公共必修课' },
          { value: 60, name: '专业必修课' },
          { value: 18, name: '专业选修课' },
          { value: 10, name: '通识选修课' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  chartInstance.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    chartInstance.resize()
  })
}

// 组件挂载
onMounted(() => {
  // 初始化图表
  initYearDistributionChart()
  initCategoryDistributionChart()
})
</script>

<style scoped>
.credits-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.credit-overview {
  margin-bottom: 30px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100%;
}

.total-credits {
  background-color: #ecf5ff;
}

.gpa {
  background-color: #f0f9eb;
}

.remaining {
  background-color: #fdf6ec;
}

.stat-icon {
  font-size: 40px;
  margin-right: 20px;
}

.total-credits .stat-icon {
  color: #409eff;
}

.gpa .stat-icon {
  color: #67c23a;
}

.remaining .stat-icon {
  color: #e6a23c;
}

.stat-content {
  flex: 1;
}

.stat-title {
  font-size: 16px;
  color: #606266;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.warning-value {
  color: #f56c6c;
}

.stat-description {
  font-size: 14px;
  color: #909399;
}

.credit-progress,
.credit-distribution,
.credit-details {
  margin-top: 30px;
}

.credit-progress h3,
.credit-distribution h3,
.credit-details h3 {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  color: #303133;
}

.progress-item {
  margin-bottom: 20px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
  color: #606266;
}

.progress-description {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}

.category-progress {
  margin-top: 20px;
}

.chart-container {
  height: 350px;
  width: 100%;
}

.failed-grade {
  color: #F56C6C;
  font-weight: bold;
}
</style> 